#include "Animation.h"
#include <cassert>


CAnimation::CAnimation()
//: Listener(this)
{
	//Listener::RegisterForEvent("STOP_PLAYING");
}


CAnimation::~CAnimation()
{
	//Listener::UnregisterFromEvent("STOP_PLAYING");
}

void CAnimation::Update(float elapsedTime)
{
	// Is paused true?
	if (m_bPlaying == false)
		return;

	// Increase the timer
	m_fTimeWaited += elapsedTime * m_fSpeed;

	// Is it time to move to the next frame?
	if (m_fTimeWaited >= vFrames[m_nCurrFrame].GetDuration())
	{
		m_fTimeWaited = 0.0f;
		++m_nCurrFrame;

		// Has it reached the end?
		if (m_nCurrFrame == vFrames.size())
		{
			// Should the animation loop from the beginning?
			if (m_bLooping == true)
				m_nCurrFrame = 0;
			else
			{
				// Stop on the last valid frame
				--m_nCurrFrame;
				m_bPlaying = false;
				m_bFinished = true;
			}
		}
		if (vFrames[m_nCurrFrame].cTrigger != "")
		{
			SGD::Event* assesThreat = new SGD::Event(vFrames[m_nCurrFrame].cTrigger.c_str(), nullptr, this);
			SGD::EventManager::GetInstance()->QueueEvent(assesThreat);
		}
	}
}

void	CAnimation::Render(SGD::Point position, bool flipped,
	float scale, SGD::Color color)
{
	assert(m_hImage != SGD::INVALID_HANDLE
		&& "AnchorPointAnimation::Render - image was not initialized!");


	// Is the color invisible? Or is the scale invisible?
	if (color.alpha == 0 || scale == 0.0f)
		return;

	if (this->IsPlaying() == false)
		return;

	// Retrieve the source rect for the current frame
	SGD::Rectangle	frame = vFrames[m_nCurrFrame].GetRect();
	SGD::Point		anchor = vFrames[m_nCurrFrame].GetAnchor();


	// Store the X-scale for flipping
	float scaleX = scale;

	if (flipped == true)
		scaleX = -scaleX;


	// Offset the given position parameters by the 
	// frame's anchor-point to get to the top-left corner
	SGD::GraphicsManager::GetInstance()->DrawTextureSection(
		m_hImage,
		{ position.x - (anchor.x * scaleX),
		position.y - (anchor.y * scale) },
		frame,
		0.0f, {},
		color, { scaleX, scale });
}

SGD::Rectangle CAnimation::GetCurrActiveRect(int num)
{
	return this->vFrames[m_nCurrFrame].GetActiveRect(num);
}

int CAnimation::GetNumActiveRects()
{
	 return this->vFrames[m_nCurrFrame].GetNumActiveRects();
}

SGD::Rectangle CAnimation::GetCurrPassiveRect()
{
	return this->vFrames[m_nCurrFrame].GetPassiveRect();
}

void CAnimation::HandleEvent(const SGD::Event* pEvent) /*override*/
{
	if (pEvent->GetEventID() == "STOP_PLAYING")
		this->m_bPlaying = false;
}
